const main = document.querySelector("main");
let codeArr = [0];
let picBase64 = [];
// 引用头部文件
import { getdata } from "./headCreate.js";

// 平滑过渡效果 (标题框)
function delayEffect() {
  let  title = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelectorAll("li")[0].querySelector("div");
  title.className = "main-Prompt-boxNone";
  
  setTimeout(() => {
    title.className = "main-Prompt-box";
  }, 0);    
}
// 显示获取本地图片
function pictureAcquisition() {  
  let pic = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelectorAll("li")[4];  
  let picBox = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelector(".main-picture-acquisition");  
  let picBoxSwitch = picBox.querySelector(".picture-acquisition-switch");

  pic.addEventListener("click", () => {
    picBox.className = "main-picture-acquisition main-picture-acquisitionBlock";
  });
  picBoxSwitch.addEventListener("click", () => {
    picBox.className = "main-picture-acquisition main-picture-acquisitionNone";
  });
}


/* -------------------------------- 功能区 -------------------------------- */
// 无序链表 插入到输入框Unordered list
function unorderedListFunction() {
  let text = main.querySelector(".left-InputArea").querySelector("#texts");
  let unorderedList = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelectorAll("li")[6];

  unorderedList.onclick = function() {
    text.focus();
    text.value += "·~.";
  }
}
// 无序链表 插入到输入框Unordered list
function unorderedListFunctionShow(arrStr, outputFrame) {  
  let arr = [];
  let arrs = [];
  let j = 0;
  
  for(let i = 0; i < arrStr.length; i++) {    
    if(arrStr[i]+arrStr[i+1]+arrStr[i+2] === "·~.") { j++; };

    if(j === 0) { arr.push(arrStr[i]); }
    else if(j === 1) { arrs.push(arrStr[i]); }
  };

  if(j === 1) {
    let ps = document.createElement("p");
    ps.innerHTML = `<span style="float: left;">${arr.join("")}</span><li style="list-style-type: disc; float: left">${arrs.join("").slice(3)}</li>`
    ps.style.overflow = "hidden";
    console.log(ps);
    outputFrame.appendChild(ps);
    
    arrStr = "";
  }
  return arrStr;
}

// 有序链表功能 插入到输入框
function orderedListFunction() {
  let text = main.querySelector(".left-InputArea").querySelector("#texts");
  let orderedList = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelectorAll("li")[5];

  orderedList.onclick = function() {
    text.focus();
    text.value += "1~.";
  }
}
// 有序链表功能 插入到输出框
function orderedListFunctionShow(arrStr, outputFrame) {
  let arr = [];
  let arrs = [];
  let j = 0;
  for(let i = 0; i < arrStr.length; i++) {    
    if(arrStr[i]+arrStr[i+1]+arrStr[i+2] === "1~.") { j++; };

    if(j === 0) { arr.push(arrStr[i]); }
    else if(j === 1) { arrs.push(arrStr[i]); }
  };

  if(j === 1) {
    let ps = document.createElement("p");
    ps.innerHTML = `<span style="float: left;">${arr.join("")}</span><li style="list-style-type: decimal-leading-zero; float: left">${arrs.join("").slice(3)}</li>`
    ps.style.overflow = "hidden"
    outputFrame.appendChild(ps);
    
    arrStr = "";
  }
  return arrStr;
}

// 图片功能 插入到输出框
function pictureFunctionShow() {  
  let text = main.querySelector(".left-InputArea").querySelector("#texts");
  let outputFrame = main.querySelector(".right-outputFrame");
  let files = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelector(".main-picture-acquisition").querySelector(".file_input").querySelector("input");
  
  // 选择图片
  if(typeof FileReader==='undefined'){ 
    result.innerHTML = "抱歉，你的浏览器不支持 FileReader"; 
    files.setAttribute('disabled','disabled'); 
  }else{ 
    files.addEventListener('change', function (){ 
      var file = this.files[0];       
      if(!/image\/\w+/.test(file.type)){ 
          alert("文件必须为图片！"); 
          return false; 
      } 
      
      var reader = new FileReader();       
      reader.readAsDataURL(file); 
      
      // 加载图片
      const p = new Promise((resolve, reject) => {
        reader.onload = function(e){
          resolve({ "result": this.result, "name": file.name });                    
        };      
      });
      p.then(value => {
        // 存储到全局
        picBase64.push(value);
        let imgs = document.createElement("img");
        imgs.src = value.result.replace(/\+/g, "%2B");
        imgs.id = "pictureFunction";
        outputFrame.appendChild(imgs);
        // 文本框标识
        text.value += value.name + "\n";
      }).catch(err => {
        console.log(err);
      });       
    },false); 
  }  
}
// 图片功能 插入到输入框
function pictureFunction(arrStr, outputFrame) {
  picBase64.forEach((element) => {
    if(arrStr === element.name) {
      let imgs = document.createElement("img");
      imgs.src = element.result;
      imgs.id = "pictureFunction";
      outputFrame.appendChild(imgs);
 
      arrStr = "";
    }  
  });
  
  return arrStr;
}

// 代码块 插入到输入框
function codeFunction() {
  let text = main.querySelector(".left-InputArea").querySelector("#texts");
  let code = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelectorAll("li")[3];

  code.onclick = function() {
    text.focus();
    text.value += "---->----\n\n---->----";
  }
}
// 代码块 插入到输出框
function codeFunctionShow(arrShow, outputFrame) { 
  if(arrShow === "---->----") {
    codeArr[0] += 1;
    
    if(codeArr[0] === 2) codeArr[0] = 0;
    return "";
  } else if(codeArr[0] === 1) {
    let ps = document.createElement("p");        
    
    ps.id = "codeFunction";    
    ps.innerHTML = arrShow;    
    outputFrame.appendChild(ps);
    return "";
  }
  
  return arrShow;
}

// 斜体功能 插入到输入框内
function italicsFunction() {
  let text = main.querySelector(".left-InputArea").querySelector("#texts");
  let italics = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelectorAll("li")[2];

  italics.onclick = function() {
    text.focus();    
    text.value += "$$";
  }
}
// 斜体功能 插入到输出框内
function italicsFunctionShow(P, arrStr) {
  if(P != undefined) {    
    let arr = [];
    let i = 0;
    let iArr = [0, 0];
    [...P.innerHTML].forEach((e, index) => {
      if(e === "$") {
        iArr[i++] = index;
        arr[index] = " ";
      }else { arr.push(e); }    
    });
    
    // 已经判定是 斜体
    if(iArr[1] != 0) {      
      arr[iArr[0]] = "<I>";
      arr[iArr[1]] = "</I>";

      let str = arr.join("");
      return str;
    }else {
      return P.innerHTML
    }    
  }else {    
    let arr = [];
    let i = 0;
    let iArr = [0, 0];
    [...arrStr].forEach((e, index) => {
      if(e === "$") {
        iArr[i++] = index;
        arr[index] = " ";
      }else { arr.push(e); }    
    });
    
    // 已经判定是 斜体
    if(iArr[1] != 0) {      
      arr[iArr[0]] = "<I>";
      arr[iArr[1]] = "</I>";

      let str = arr.join("");
      return str;
    }else {
      return arrStr
    }    
  }
}

// 加粗功能 插入到输入框内
function boldFunction() {
  let text = main.querySelector(".left-InputArea").querySelector("#texts");
  let bolds = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelectorAll("li")[1];

  bolds.onclick = function() {
    text.focus();    
    text.value += "**  **";
  }
 
}
// 加粗功能 插入到输出框内
function boldFunctionShow(arrStr, outputFrame) {
  let arrStrs = arrStr;
  let counting = 0;
  let arr = ["**&emsp;", "&emsp;**"];
  let str1 = ["",];
  let text = ["",];
  // 生成p标签赋值与插入输出框
  let p = document.createElement(`p`);   
  // 生成b标签
  let b = document.createElement(`b`);
  let sum = [];

  // 分割加粗字段
  let i = 0;
  let j = 0;
  let n = 0;
    for(i = 0; i < arrStr.length; i++) {
      if(arrStr[i]+arrStr[i + 1]+arrStr[i + 2]+arrStr[i + 3]+arrStr[i + 4]+arrStr[i + 5]+arrStr[i + 6]+arrStr[i + 7] === arr[counting]) {
        counting++;
        arrStr = arrStr.slice(i + 8, arrStr.length);        
        i--;

        if(counting === 2) {
          sum[++n] = b;
          b = document.createElement(`b`);
          
          if(arrStr.length > 0) {
            i = -1;
            j++;
            counting = 0;
            str1[j] = text[j] = "";            
            
            n++;
          }
        }
      }else if(counting === 0) {
        str1[j] += arrStr[i];

        arrStr = arrStr.slice(1, arrStr.length);
        sum[n] = str1[j];
        i--;
        
      }else if(counting === 1) {
        text[j] += arrStr[i];
        arrStr = arrStr.slice(1, arrStr.length);
        b.innerHTML = text[j];       
        i--;
      }   
    }

    // 赋值生成DOM节点
    if(n !== 0) {         
      for(let i = 0; i < sum.length; i++) {
        if(sum[i] != undefined) {
          if(typeof sum[i] != "string") {
            p.appendChild(sum[i]);
          }else {
            p.innerHTML += sum[i];
          }
        }        
        
      }      
      // 查看是否有斜体
      p.innerHTML = italicsFunctionShow(p);
      // outputFrame.appendChild(p);
      return p.innerHTML;
    }else {
      return arrStrs;
    }
}

// 标题功能 插入到输入框内
function titleFunction() {  
  let titles = main.querySelector(".top-navigation").querySelector(".main-left-box").querySelectorAll("li")[0].querySelector(".main-Prompt-box").querySelectorAll("span");
  let text = main.querySelector(".left-InputArea").querySelector("#texts");
  
  // 光标聚焦
  text.focus();
  // 添加选中的标签符号
  for(let i = 0; i < titles.length; i++) {        
    titles[i].onclick = function() {
      if(titles[i] === titles[0]) {        
        text.value = text.value + "# ";
        text.focus();
        // 平滑过渡效果
        delayEffect();
      }else if(titles[i] === titles[1]) {
        text.value = text.value + "## ";
        text.focus();
        // 平滑过渡效果
        delayEffect();      
      }else if(titles[i] === titles[2]) {
        text.value = text.value + "### ";
        text.focus();
        // 平滑过渡效果
        delayEffect();
      }else if(titles[i] === titles[3]) {
        text.value = text.value + "#### ";
        text.focus();
        // 平滑过渡效果
        delayEffect();
      }else if(titles[i] === titles[4]) {
        text.value = text.value + "##### ";
        text.focus();
        // 平滑过渡效果
        delayEffect();
      }else if(titles[i] === titles[5]) {
        text.value = text.value + "###### ";
        text.focus();
        // 平滑过渡效果
        delayEffect();
      }else if(titles[i] === titles[6]) {
        text.value = text.value + "####### ";
        text.focus();
        // 平滑过渡效果
        delayEffect();
      }
    } 
  }
  
}
// 标题功能 插入输出框内
function titleFunctionShow(arrStr, outputFrame, symbol) {
  function countSubstr(str, substr) {
    var reg = new RegExp(substr, "g");       
    return str.match(reg) ? str.match(reg).length : 0;
  }
  if(countSubstr(arrStr, symbol) != 0) {       
    // 将标题符号去除
    let sumStr = arrStr; arrStr = "";     
    let str = symbol;
    let j = 0;
    for(let n = 0; n < sumStr.length; n++) {
      if(sumStr[n] === str[j]) {        
        j++;       
      } else arrStr += sumStr[n];
    }
    
    // 生成h标签
    let hs = document.createElement(`h${j - 6}`);
    hs.innerHTML = arrStr;
    outputFrame.appendChild(hs);
    
    // 赋空
    arrStr = "";
  }


  return arrStr;
}

// 写作功能
function writingFunctions() {
  let effect = main.querySelector(".top-navigation").querySelector(".effect");
  let text = main.querySelector(".left-InputArea").querySelector("#texts");

  let outputFrame = main.querySelector(".right-outputFrame");
  let arr = [];

  /* --------- 输入输出 --------- */ 
  effect.onclick = function() {
    let str = "";
    let titleSymbol = ["#&emsp;", "##&emsp;", "###&emsp;", "####&emsp;", "#####&emsp;", "######&emsp;"];
    /* -------------- 整理数据 -------------- */ 
    for(let i = 0; i < text.value.length; i++) {
      if(text.value[i] === "\n") {
        str += ",";
      }else {
        if(text.value[i] === " ") {
          str += "&emsp;";
        }else {
          str += text.value[i];
        }
        
      }
    }
    arr = str.split(",");
    /* -------------- 整理数据 -------------- */

    /* -------------- 删除元素 -------------- */
    main.removeChild(outputFrame);

    outputFrame = document.createElement("article");
    main.appendChild(outputFrame);
    outputFrame.className = "right-outputFrame";       
    /* -------------- 删除元素 -------------- */
    

    
    /* -------------- 生成元素 -------------- */    
    for(let i = 0; i < arr.length; i++) {      
      // 查找 h1~h6标题
      for(let j = titleSymbol.length - 1; j >= 0; j--) {        
        if(arr[i] === "") {
          break;
        }
        // 查找 标题是否在输入框内
        arr[i] = titleFunctionShow(arr[i], outputFrame, titleSymbol[j]);        
      }
      

     
      // 查看是否为图片
      if(arr[i] != "") arr[i] = pictureFunction(arr[i], outputFrame);
      // 查看是否为加粗
      if(arr[i] != "") arr[i] = boldFunctionShow(arr[i], outputFrame);
      // 查看是否为斜体
      if(arr[i] != "") arr[i] = italicsFunctionShow(undefined ,arr[i]);
      // 查看是否为代码块
      if(arr[i] != "") arr[i] = codeFunctionShow(arr[i], outputFrame);
      // 查看是否为有序链表
      if(arr[i] != "") arr[i] = orderedListFunctionShow(arr[i], outputFrame);
      // 查看是否为无序链表
      if(arr[i] != "") arr[i] = unorderedListFunctionShow(arr[i], outputFrame);
      
      // 查找 p正文
      if(arr[i] != "") {
        let ps = document.createElement("p");        
        
        ps.innerHTML = arr[i];
        outputFrame.appendChild(ps);
      }      
    }
    /* -------------- 生成元素 -------------- */
    
    // 获取数据
    getdata(outputFrame);
  }
  /* --------- 输入输出 --------- */
}
/* -------------------------------- 功能区 -------------------------------- */



// 无序链表功能
unorderedListFunction();
// 有序链表功能
orderedListFunction();
// 图片功能
pictureFunctionShow();
// 代码块功能
codeFunction();
// 斜体功能
italicsFunction();
// 加粗功能
boldFunction();
// 标题功能
titleFunction();
// 写作功能
writingFunctions();



// 显示获取本地图片
pictureAcquisition();

